package com.steakliu.sun.client.spring;

import com.steakliu.sun.annotation.SunReference;
import com.steakliu.sun.client.api.ClientConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-13  23:18
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Component
public class SunFactoryPostProcessor implements ApplicationContextAware,BeanClassLoaderAware, BeanFactoryPostProcessor {

    private ClassLoader classLoader;
    private ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] definitionNames = beanFactory.getBeanDefinitionNames();
        for (String definitionName : definitionNames) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(definitionName);
            String beanClassName = beanDefinition.getBeanClassName();
            if (null != beanClassName) {
                Class<?> clazz = ClassUtils.resolveClassName(beanClassName, classLoader);
                ReflectionUtils.doWithFields(clazz, field -> {
                    SunReference reference = field.getAnnotation(SunReference.class);
                    if (null != reference) {
                        String beanName = field.getName();
                        //Spring容器中不存在此bean，则注册
                        if (!applicationContext.containsBean(beanName)) {
                            BeanDefinition definition = this.buildBeanDefinition(reference, field);
                            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                            registry.registerBeanDefinition(beanName, definition);
                        }
                    }
                });
            }
        }
    }

    private BeanDefinition buildBeanDefinition(SunReference reference, Field field) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(SunFactoryBean.class);
        ClientConfig clientConfig = ClientConfig
                .builder()
                .version(reference.version())
                .group(reference.group())
                .registryType(reference.registryType())
                .registryAddress(reference.registryAddress())
                .serializer(reference.serializer())
                .proxy(reference.proxy())
                .timeout(reference.timeout())
                .async(reference.async())
                .oneway(reference.oneway())
                .loadBalance(reference.loadBalance())
                .cache(reference.cache())
                .cacheTime(reference.cacheTime())
                .useFlowControl(reference.useFlowControl())
                .flowControlType(reference.flowControlType())
                .reflectType(reference.reflectType())
                .retries(reference.retries())
                .retryInterval(reference.retryInterval())
                .token(reference.token())
                .directConnections(reference.directConnections())
                .useRateLimit(reference.useRateLimit())
                .rateLimiterType(reference.rateLimiterType())
                .milliseconds(reference.milliseconds())
                .permits(reference.permits())
                .build();
        builder.addPropertyValue("clientConfig", clientConfig);
        builder.setInitMethodName("init");
        builder.addPropertyValue("interfaceClass",field.getType());
        builder.addPropertyValue("fallbackClass",reference.fallbackClass());
        builder.setPrimary(true);
        return builder.getBeanDefinition();
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
